package com.lfx.concurrent;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;

public class CompletTableFutureMain8 {


    private static Random random = new Random();

    private static volatile Integer result = 0;

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        CompletableFuture[] completableFutures = new CompletableFuture[10];

        for (int i = 0; i < 10; i++) {
            CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1000 + random.nextInt(1000));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    result++;
                }
            });
            completableFutures[i]=voidCompletableFuture;
        }

        System.out.println(result);

//        for (CompletableFuture completableFuture : completableFutures) {
//            Object o = completableFuture.get();
//            System.out.println(result);
//
//        }

//
//        CompletableFuture<Integer> integerCompletableFuture = CompletableFuture.allOf(completableFutures).thenApply(new Function<Void, Integer>() {
//            @Override
//            public Integer apply(Void unused) {
//                return result;
//            }
//        });
//
//        Integer integer = integerCompletableFuture.get();
//        System.out.println("最终结果:"+integer);


        CompletableFuture<Integer> integerCompletableFuture = CompletableFuture.anyOf(completableFutures).thenApply(new Function<Object, Integer>() {
            @Override
            public Integer apply(Object object) {
                System.out.println(object);
                return result;
            }
        });
        Integer integer = integerCompletableFuture.get();
        System.out.println("最终结果:"+integer);

    }
}
